package org.cheetah.core.action.spi;

import javax.xml.bind.annotation.XmlAccessOrder;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorOrder;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import org.cheetah.core.action.Action;
import org.cheetah.core.action.ActionContext;
import org.cheetah.core.action.ActionDefinition;
import org.cheetah.core.endpoint.EndpointProducer;
import org.cheetah.core.endpoint.Endpoints;
import org.cheetah.core.exchange.Exchange;

@XmlRootElement(name = "to")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)
public class ToDefinition extends ActionDefinition {

	@XmlAttribute(name = "uri", required = true)
	private String uri;

	public ToDefinition uri(String uri) {
		this.uri = uri;
		return this;
	}

	public Action createAction() throws Exception {
		return new ActionImpl(Endpoints.createProducer(uri));
	}

	private static class ActionImpl implements Action {
		private EndpointProducer producer;

		ActionImpl(EndpointProducer producer) {
			this.producer = producer;
		}

		public void process(ActionContext ctx, Exchange exchange)
				throws Exception {
			producer.send(exchange);
			ctx.process(exchange);
		}
	}
}
